//
//  HTDetialMapLineVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/30.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTDetialMapLineVC.h"
//高德地图
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import <MapKit/MapKit.h>

#import "CommonUtility.h"
#import "MANaviRoute.h"


@interface HTDetialMapLineVC()<AMapSearchDelegate,MAMapViewDelegate>
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;
@property (weak, nonatomic) IBOutlet UILabel *bottomLabel;


//路径规划
@property (nonatomic, strong) AMapSearchAPI *search;


/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/* 用于显示当前路线方案. */
@property (nonatomic) AMapPath *mapPath;
@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;


@end

@implementation HTDetialMapLineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详细路线";
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    [self configNav];
    [self configMap];
    
}
- (void)configInitData{
    self.bottomHeight.constant = 0;
    self.bottomLabel.text = @"此路线的里程大约为：0公里";
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self choiceFunction];
}
- (void)configNav{
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"规划" style:UIBarButtonItemStyleDone target:self action:@selector(choiceFunction)];
    self.navigationItem.rightBarButtonItem = right;
}
- (void)choiceFunction{
    [self configInitData];
    [UIAlertController alertStyleShowInController:self title:@"请选择" message:@"选择路线规划方式" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        [alertActions addObject:[UIAlertAction actionWithTitle:@"避免拥堵" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self clear];
            [self searchRoutePlanningDriveWithStrategy:4];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"时间优先" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self clear];
            [self searchRoutePlanningDriveWithStrategy:0];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"距离最短" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self clear];
            [self searchRoutePlanningDriveWithStrategy:2];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"较少费用" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self clear];
            [self searchRoutePlanningDriveWithStrategy:1];
        }]];
    } completion:nil];
}
- (void)configMap{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    self.mapView.showsCompass = NO;
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    CLGeocoder *geoC = [[CLGeocoder alloc] init];
    [geoC geocodeAddressString:self.startName completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        if(error == nil)
        {
            self.startCoordinate = pl.location.coordinate;
            [geoC geocodeAddressString:self.endName completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                CLPlacemark *pl = [placemarks firstObject];
                
                if(error == nil)
                {
                    self.destinationCoordinate = pl.location.coordinate;
                    [self addDefaultAnnotations];
                }
            }];
        }
    }];
}
- (void)searchRoutePlanningDriveWithStrategy:(NSInteger)strategy
{
    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    navi.strategy = strategy;
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapDrivingRouteSearch:navi];
}

#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 5;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.image = nil;
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }
        else
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:@"起始点"])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"startPoint"];
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:@"终点"])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"endPoint"];
            }
            
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    DBLog(@"Error: %@", error);
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    if (response.count > 0)
    {
        self.mapPath = response.route.paths[0];
        [self presentCurrentCourse];
    }
}

#pragma mark -- 工具

- (void)addDefaultAnnotations
{
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = @"起始点";
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      = @"终点";
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    [self.mapView addAnnotation:startAnnotation];
    [self.mapView addAnnotation:destinationAnnotation];
}
/* 展示当前路线方案. */
- (void)presentCurrentCourse
{
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    self.naviRoute = [MANaviRoute naviRouteForPath:self.mapPath withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.startAnnotation.coordinate.latitude longitude:self.startAnnotation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destinationAnnotation.coordinate.latitude longitude:self.destinationAnnotation.coordinate.longitude]];
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                        edgePadding:UIEdgeInsetsMake(0, 0, 0, 0)
                           animated:YES];
    self.bottomHeight.constant = 55.f;
    self.bottomLabel.text = [NSString stringWithFormat:@"此路线的里程大约为：%.2f公里",self.mapPath.distance/1000.0];
}

/* 清空地图上已有的路线. */
- (void)clear
{
    if (self.naviRoute) {
         [self.naviRoute removeFromMapView];
    }
}





@end
